package com.yuanye.gwcit.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.yuanye.gwcit.R;
import com.yuanye.gwcit.adapter.NumberKeyAdapter;
import com.yuanye.yeecho.base.BaseFragment;

import java.util.Random;

public class HeadsetFragment extends BaseFragment {
    final String TAG = HeadsetFragment.class.getSimpleName();

    public HeadsetFragment() {
        setTaskName("耳机");
    }
    private Handler handler;
    int[] audios = {R.raw.num1, R.raw.num2, R.raw.num3, R.raw.num4, R.raw.num5, R.raw.num6, R.raw.num7, R.raw.num8, R.raw.num9};
    Random rand = new Random();
    int indexL = 0;
    int indexR = 0;

    private TextView textView;
    private GridView gridView;
    private Button btnTest;
    private MediaPlayer mediaPlayer;
    private HeadphoneReceiver headphoneReceiver;
    private AudioManager audioManager;
    private boolean isPlayLeft = true;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_headset, container, false);
        textView = view.findViewById(R.id.tvTips);
        gridView = view.findViewById(R.id.gridView);
        handler = new BtnHandler();
        NumberKeyAdapter adapter = new NumberKeyAdapter(getContext(), handler);
        gridView.setAdapter(adapter);
        audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        return view;
    }

    @Override
    public void execTask() {
        lock();
        boolean flag = audioManager.isWiredHeadsetOn();
        Log.d(TAG, "耳机是否插入:"+flag);
        if (flag){
            textView.setText("耳机已连接, 请根据听到的数字点击对应按钮");
            textView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    gridView.setVisibility(View.VISIBLE);
                    playAudioLeft();
                }
            },1000);

        }else{
            textView.setText("请插入耳机");
            //注册广播
            IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
            if (headphoneReceiver == null){
                headphoneReceiver = new HeadphoneReceiver();
                getContext().registerReceiver(headphoneReceiver, filter);
            }
        }

    }

    @Override
    public void stopTask() {
        unlock();
        if (headphoneReceiver != null) {
            getContext().unregisterReceiver(headphoneReceiver);
            headphoneReceiver = null;
        }
        if (mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public void playAudioLeft(){
        isPlayLeft = true;
        indexL = rand.nextInt(9);
        Log.d(TAG, "左声道随机值:"+indexL);
        textView.post(new Runnable() {
            @Override
            public void run() {
                textView.setText("左声道");
            }
        });
        if (mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
        mediaPlayer = MediaPlayer.create(getContext(), audios[indexL]);
        mediaPlayer.setVolume(1.0f, 0.0f);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });
        mediaPlayer.start();
    }

    public void playAudioRight(){
        isPlayLeft = false;
        indexR = rand.nextInt(9);
        textView.post(new Runnable() {
            @Override
            public void run() {
                textView.setText("右声道");
            }
        });
        Log.d(TAG, "右声道随机值:"+indexR);
        if (mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
        mediaPlayer = MediaPlayer.create(getContext(), audios[indexR]);
        mediaPlayer.setVolume(0.0f, 1.0f);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });
        mediaPlayer.start();
    }

    class BtnHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.d(TAG, "handleMessage: "+msg.what);
            int key = msg.what;
            if (mediaPlayer != null){
                mediaPlayer.release();
                mediaPlayer = null;
                if (isPlayLeft){
                    if (key == indexL){
                        textView.setText("左声道PASS");
                        gridView.setVisibility(View.INVISIBLE);
                        postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                gridView.setVisibility(View.VISIBLE);
                                playAudioRight();
                            }
                        }, 300);

                    }else{
                        textView.setText("测试失败，请点击测试按钮重新开始");
                        setFail();
                        stopTask();
                    }
                }else{
                    if (key == indexR){
                        textView.setText("测试通过");
                        gridView.setVisibility(View.INVISIBLE);
                        passAndNext();
                    }else{
                        textView.setText("测试失败，请点击测试按钮重新开始");
                        setFail();
                    }
                }

            }

        }
    }

    class HeadphoneReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                int state = intent.getIntExtra("state", -1);
                if (state == 0) {
                    // 耳机拔出
//                    Toast.makeText(context, "请插入耳机", Toast.LENGTH_SHORT).show();

                } else if (state == 1) {
                    // 耳机插入
//                    Toast.makeText(context, "耳机已连接", Toast.LENGTH_SHORT).show();
                    execTask();
                }
            }
        }
    }
}
